# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'WF69986': {
        'API_KEY': 'CV5RBF8XNU7PES9PYROVJRBIAMPUYGJA',
        'gateway': 'https://pay.llsyqm.com/uniThirdPay'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _gen_nofify_sign_str(data):
    return "%s%s%s%s%s%s" % \
           (
               data[u'amt'],
               data[u'merchOrderId'],
               data[u'orderId'],
               data[u'orderStatusMsg'],
               data[u'status'],
               data[u'tranTime'],
           )


def verify_notify_sign(params, key):
    s = _gen_nofify_sign_str(params)
    calculated_sign = generate_sign(s + key)
    if params[u'md5value'] != calculated_sign:
        _LOGGER.info("wufupay sign: %s, calculated sign: %s", params[u'md5value'], calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _gen_sign_str(data):
    return "%s%s%s%s%s%s%s%s%s" % \
           (
               data['amt'],
               data['merId'],
               data['merchOrderId'],
               data['notifyUrl'],
               data['pName'],
               data['retUrl'],
               data['showCashier'],
               data['svcName'],
               data['tranType'],
           )


def _get_pay_type(service):
    if service == 'qq':
        return 'QQ_H5'
    elif service == 'jd':
        return 'JD_H5'
    elif service == 'alipay':
        return 'ALIPAY_H5'
    else:
        return 'QQ_H5'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('svcName', 'UniThirdPay'),
        ('merId', mch_id),
        ('merchOrderId', str(pay.id)),
        ('tranType', _get_pay_type(service)),
        ('pName', 'recharge'),
        ('showCashier', 0),
        ('amt', str(int(pay_amount * 100))),
        ('notifyUrl', '{}/pay/api/{}/wufupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('retUrl', '{}/pay/api/{}/wufupay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
    ))
    s = _gen_sign_str(parameter_dict)
    sign = generate_sign(s + key)
    parameter_dict['md5value'] = sign
    _LOGGER.info("wufupay create charge data: %s", parameter_dict)
    response = requests.post(_get_gateway(mch_id), data=parameter_dict, timeout=3, allow_redirects=False)
    _LOGGER.info("wufupay create rsp data: %s %s", response.status_code, response.text)
    cache_id = redis_cache.save_html(pay.id, response.text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("wufupay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data[u'merchOrderId']
    if not pay_id:
        _LOGGER.error("fatal error, wufupay out_trade_no not exists, data: %s" % data)
        raise ParamError('wufupay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data[u'status'])
    total_fee = float(data['amt']) / 100
    trade_no = ''

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 0:
        _LOGGER.info('wufupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)
